/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder == null || postorder == null) {
            return null;
        }
        return buildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }

    private TreeNode buildTree(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd) {
        if (inStart > inEnd || postStart > postEnd || inStart > inorder.length - 1 || postStart > postorder.length - 1) {
            return null;
        }
        TreeNode node = new TreeNode(postorder[postEnd]);
        for (int i = inStart; i <= inEnd; i++) {
            if (node.val == inorder[i]) {
                int leftTreeSize = i - inStart;
                node.left = buildTree(inorder, inStart, i - 1, postorder, postStart, postStart + leftTreeSize - 1);
                node.right = buildTree(inorder, i + 1, inEnd, postorder, postStart + leftTreeSize, postEnd - 1);
                break;
            }
        }
        return node;
    }
}
